package com.example.test.advice.第五章_数组和集合.建议80_多线程使用Vector或HashTable;

import java.util.*;

/**
 * 本例问题并非线程安全问题，而是同步修改问题
 */
public class Client {

    public static void main(String[] args) {
        test3();
    }

    //同步修改问题
    private static void test(){
        //火车票列表
        final List<String> tickets = new ArrayList<>();
        //初始化票据池
        for(int i = 0;i < 10000;i++){
            tickets.add("火车票"+i);
        }

        //退票
        Thread returnThread = new Thread(() -> {
            while (true){
                tickets.add("火车票"+new Random().nextInt());
            }
        });

        //售票
        Thread saleThread = new Thread(() -> {
            for(String ticket:tickets){
                tickets.remove(ticket);
            }
        });

        returnThread.start();
        saleThread.start();
    }

    private static void test2(){
        //火车票列表
        final List<String> tickets = new ArrayList<>();
        //初始化票据池
        for(int i = 0;i < 100000;i++){
            tickets.add("火车票"+i);
        }

        for(int i = 0;i < 10;i++){
            new Thread(() -> {
                while(true){
                    System.out.println(Thread.currentThread().getId()+"---"+tickets.remove(0));
                }
            }).start();
        }
    }

    private static void test3(){
        //火车票列表
        final Vector<String> tickets = new Vector<>();
        //初始化票据池
        for(int i = 0;i < 100000;i++){
            tickets.add("火车票"+i);
        }

        for(int i = 0;i < 10;i++){
            new Thread(() -> {
                while(true){
                    System.out.println(Thread.currentThread().getId()+"---"+tickets.remove(0));
                }
            }).start();
        }
    }
}
